package com.xiaoxu.maxTemp;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;


public class MaxTemperatureMapper extends Mapper<LongWritable,Text,Text,IntWritable>{

    private static final int MISSING = 9999;

    /**
     * ab1995c+00051
     * ab1995c-00026
     * ab1995c+00021
     * ab1995c-00006
     * ab1993c+99991  --MISSING（丢失）数据
     * ab1994c+00025
     * ab1994c-00084
     *
     * @param key
     * @param value
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    /**
     *  RecordReader<K,V>
     * （key(偏移量)，value）
     * （0，ab1995c+00051）
     * （13，ab1995c-00026）
     * （26，ab1995c+00021）
     */
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //key = 0 value = "ab1995c+00051"
        //line = "ab1995c+00051"
        String line = value.toString();
        //year = 1995
        String year = line.substring(2, 6);
        int airTemperature;
        //做正负判断，避免截取字符'+',节省网络开销和内存开销
        if (line.charAt(7) == '+'){
            //line.substring(9, 13) = 0005
            airTemperature = Integer.parseInt(line.substring(9, 13));
        }else {
            //line.substring(9, 13) = -0002
            airTemperature = Integer.parseInt(line.substring(8,13));
        }
        //quality = 1 / 6
         String quality = line.substring(13,14);

        if (airTemperature != MISSING && quality.matches("[01459]")){
            //-------------------year = 1995 -----------airTemperature=5
            //-------------------year = 1995 -----------airTemperature=-2
            context.write(new Text(year), new IntWritable(airTemperature));
        }
    }
}
